/**
  ******************************************************************************
  * File Name   : ethif.c
  * Description : 提供对其他任务使用的线程安全的应用接口
  ******************************************************************************
  * @attention
  * 前缀说明
  * ethos: 系统层接口,仅供ethernet任务使用
  * ethif: 应用层接口,可供其他任务调用
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "bsp.h"
#include "tskcfg.h"
#include "ethernet.h"
#include <string.h>

volatile uint8_t ethif_get_sr[_WIZCHIP_SOCK_NUM_] = {0, 0, 0, 0}; /* 该变量必须为 volatile */

void ethif_socket(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag)
{
  Ethernet_CtrlQueStru ctrl;

  memset(&ctrl, 0, sizeof(ctrl));

  ctrl.type = ETH_CRTL_SOCKET;
  ctrl.sn = sn;
  ctrl.protocol = protocol;
  ctrl.local_port = port;
  ctrl.flag = flag;

  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);
}

void ethif_close(uint8_t sn)
{
  Ethernet_CtrlQueStru ctrl;

  memset(&ctrl, 0, sizeof(ctrl));

  ctrl.type = ETH_CRTL_CLOSE;
  ctrl.sn = sn;
  
  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);
}

void ethif_listen(uint8_t sn)
{
  Ethernet_CtrlQueStru ctrl;

  memset(&ctrl, 0, sizeof(ctrl));

  ctrl.type = ETH_CRTL_LISTEN;
  ctrl.sn = sn;

  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);
}

void ethif_connect(uint8_t sn, const uint8_t *addr, uint16_t port)
{
  Ethernet_CtrlQueStru ctrl;

  memset(&ctrl, 0, sizeof(ctrl));

  ctrl.type = ETH_CRTL_CONNECT;
  ctrl.sn = sn;
  ctrl.dest_ip[0] = addr[0];
  ctrl.dest_ip[1] = addr[1];
  ctrl.dest_ip[2] = addr[2];
  ctrl.dest_ip[3] = addr[3];
  ctrl.dest_port  = port;

  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);
}

void ethif_disconnect(uint8_t sn)
{
  Ethernet_CtrlQueStru ctrl;

  memset(&ctrl, 0, sizeof(ctrl));

  ctrl.type = ETH_CRTL_DISCONNECT;
  ctrl.sn = sn;
  
  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);
}

/* 最大会阻塞127ms */
uint8_t ethif_get_socket_sr(uint8_t sn)
{
  int8_t timeout;
  Ethernet_CtrlQueStru ctrl;

  ctrl.type = ETH_CRTL_GETSOCKETSR;
  ctrl.sn = sn;
  
  timeout = 127;
  
  ethif_get_sr[sn] = 0;

  xQueueSend(ethernet_ctrl_qhd, &ctrl, 0);

  while((ethif_get_sr[sn] == 0) && (timeout-- > 0))
  {
    vTaskDelay(1);
  }

  return ethif_get_sr[sn];
}

void ethif_tosend(const Ethernet_SendQueStru *tosend)
{
  xQueueSend(ethernet_send_qhd, tosend, 0);
}
